package com.bckj.fastboot.upms.biz.service;

import com.bckj.fastboot.security.util.SecurityUtils;
import com.bckj.fastboot.upms.api.dto.PermsCreateParams;
import com.bckj.fastboot.upms.api.dto.TreeSelect;
import com.bckj.fastboot.upms.biz.core.perm.Perms;
import com.bckj.fastboot.upms.biz.core.perm.PermsHandler;
import com.bckj.fastboot.upms.biz.core.perm.model.GenTreeContext;
import com.bckj.fastboot.upms.biz.repository.SysMenuRepository;
import com.bckj.fastboot.upms.biz.convert.SysMenuConvert;
import com.bckj.fastboot.upms.api.vo.SysMenuVO;
import com.bckj.fastboot.upms.api.dto.SysMenuRequest;
import com.bckj.fastboot.upms.api.dto.SysMenuQuery;
import com.bckj.fastboot.upms.api.entity.SysMenu;

import com.bckj.fastboot.core.lang.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 菜单表(SysMenu)domain-service
 *
 * @author wfc
 * @since 2023-09-14 10:11:55
 */
@Service
@RequiredArgsConstructor
public class SysMenuService {

    private final SysMenuRepository sysMenuRepository;
	
    private final SysMenuConvert sysMenuConvert;

    private final PermsHandler permsHandler;
	
    /**
     * 列表
     *
     * @param query req
     * @return list
     */
    public List<SysMenuVO> list(SysMenuQuery query){
        return sysMenuRepository.getBaseMapper().list(query);
    }
    
     /**
     * 保存
     *
     * @param request req
     */
    public boolean save(SysMenuRequest request) {
        SysMenu entity = sysMenuConvert.request2Bean(request);
        int[] keyIndex = permsHandler.genKeyIndex(SecurityUtils.getUserOrElseThrow().getClientId(), entity.getPermsType());
        entity.setKeyIndex(keyIndex[0]);
        entity.setBitLocation(keyIndex[1]);
        return sysMenuRepository.save(entity);
    }

    /**
     * 修改
     *
     * @param request req
     */
    public boolean update(SysMenuRequest request) {
        return sysMenuRepository.updateById(sysMenuConvert.request2Bean(request));
    }
    
    /**
     * 详情
     *
     * @param id id
     * @return vo
     */
    public SysMenuVO details(Long id) {
        SysMenu bean = sysMenuRepository.getById(id);
        if (null == bean) {
            throw new BusinessException("当前对象不存在!");
        }
        return sysMenuConvert.bean2VO(bean);
    }

	/**
	 * 根据Id移除
	 *
	 * @param id id
	 * @return boolean
	 */
	public boolean remove(Long id) {
        //TODO LIMIT
		return sysMenuRepository.removeById(id);
	}

    private List<SysMenu> listMenu(SysMenuQuery query) {
        //如果是管理员，只返回管理员菜单
        if (isAdminMenu(query)) {
            query.setIsAdmin(1);
        }
        return sysMenuRepository.getBaseMapper().listMenu(query);
    }

    private boolean isAdminMenu(SysMenuQuery query) {
        //判断用户是管理员吗
        return false;
    }

    public TreeSelect tree(SysMenuQuery query) {
        GenTreeContext ctx = new GenTreeContext();
        ctx.setPermsType(query.getPermsType());
        List<SysMenu> list = listMenu(query);
        ctx.setMenuList(list);
        if (isAdminMenu(query)) {
            return permsHandler.genTreeSelect(ctx);
        }
        boolean readOneself = true, readBindings = true;
        int dataFilter = 0;
        //permsFlag 0 全部 1 组的权限 2 自己的权限 3 自己过滤的权限
        switch (query.getPermsFlag()) {
            case 1:
                readOneself = false;
                dataFilter = 1;
                break;
            case 2:
                readBindings = false;
                dataFilter = 1;
                break;
            case 3:
                readBindings = false;
                dataFilter = 2;
                break;
        }
        ctx.setDataFilterFlag(dataFilter);
        Integer type = query.getType();
        //0 角色 1 用户
        if (type != null) {
            Perms perms = permsHandler.create(
                    new PermsCreateParams()
                            .setId(query.getId())
                            .setType(type)
                            .setPermsType(query.getPermsType())
                            .setReadOneself(readOneself)
                            .setReadBindings(readBindings)
            );
            ctx.setPerms(perms);
        }
        if (query.getFilter() != 0) {
            //该登录用户拥有的菜单树
            ctx.setFilter(query.getFilter());
            if (query.getFilter() == 2) {
                Perms userPerms = permsHandler.create(
                        new PermsCreateParams()
                                .setId(SecurityUtils.getUserOrElseThrow().getId())
                                .setType(1)
                                .setPermsType(query.getPermsType())
                                .setReadOneself(readOneself)
                                .setReadBindings(readBindings)
                );
                ctx.setUserPerms(userPerms);
            }
            return permsHandler.genTreeSelect(ctx);
        }
        //全都菜单树
        return permsHandler.genTreeSelect(ctx);
    }


    public boolean initKeyIndex(SysMenuQuery query) {
        String clientId = SecurityUtils.getUserOrElseThrow().getClientId();
        List<SysMenu> list = sysMenuRepository.lambdaQuery()
                .eq(SysMenu::getPermsType, query.getPermsType())
                .isNull(SysMenu::getKeyIndex).list();
        list.forEach(p -> {
            int[] keyIndex = permsHandler.genKeyIndex(clientId, query.getPermsType());
            sysMenuRepository.lambdaUpdate().eq(SysMenu::getId, p.getId())
                    .set(SysMenu::getKeyIndex, keyIndex[0])
                    .set(SysMenu::getBitLocation, keyIndex[1])
                    .update();
        });
        return true;
    }
}

